package com.quicklife.service.impl;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.quicklife.pojo.Tuser;
import com.quicklife.service.inter.AboutMeService;
import com.quicklife.service.inter.FileUploadService;
import com.quicklife.util.JsonUtil;
import com.quicklife.util.SqlHelper;
import com.quicklife.util.StringUtil;

/**
 * “我”模块逻辑处理
 * 
 * @author HackerD
 * 
 */
public class AboutMeServiceImpl implements AboutMeService {

	@Override
	public String modifyPsw(String rqinfos) {
		// 获取出请求信息
		JSONObject jsonObject = JSONObject.fromObject(rqinfos);
		String userId = jsonObject.getString("id");
		String opsw = jsonObject.getString("opsw");
		String npsw = jsonObject.getString("npsw");

		try {
			// 验证旧密码
			String rtinfos = SqlHelper.checkBeExist(
					"tuser where id=? and password=?", new String[] { userId,
							opsw }, StringUtil.FAIL_ODPSW_ERR);
			// rtinfos如果为空则为错误
			if (StringUtil.isNull(rtinfos)) {
				return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_FAIL,
						StringUtil.FAIL_ODPSW_ERR);
			}

			// 更新密码
			SqlHelper.executeUpdate("update tuser set password=? where id=?",
					new String[] { npsw, userId });

			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_OK,
					StringUtil.RESULT_SUCESS_UPDATE);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_FAIL,
					StringUtil.RESULT_EXCEPTION);
		}
	}

	@Override
	public String modifyInfos(HttpServletRequest request) {

		try {
			FileUploadService fileUploadService = new FileUploadServiceImpl();
			String tempInfos = fileUploadService.getUploadInfos(request);
			JSONObject jsonObject = JSONObject.fromObject(tempInfos);

			Tuser user = (Tuser) JsonUtil.toBean(
					jsonObject.getString("rqinfos"), Tuser.class);

			if (jsonObject.containsKey("photo")) {
				user.setPhoto(jsonObject.getString("photo"));
			}

			String result = null;

			// 判断登陆用户名是否已被注册
			result = SqlHelper.checkBeExist(
					"Tuser where LOGIN_NAME=? and id!=?",
					new String[] { user.getLogin_name(),
							StringUtil.toString(user.getId()) },
					StringUtil.FAIL_LNAME_EXIST);
			if (result != null) {
				return result;
			}

			// 判断昵称是否已被注册
			result = SqlHelper.checkBeExist(
					"Tuser where nickname=? and id!=?",
					new String[] { user.getNickname(),
							StringUtil.toString(user.getId()) },
					StringUtil.FAIL_NICKNAME_EXIST);
			if (result != null) {
				return result;
			}

			// 判断邮箱是否已被注册
			result = SqlHelper.checkBeExist(
					"Tuser where Email=? and id!=?",
					new String[] { user.getEmail(),
							StringUtil.toString(user.getId()) },
					StringUtil.FAIL_EMAIL_EXIST);
			if (result != null) {
				return result;
			}

			// 更新资料
			SqlHelper
					.executeUpdate(
							"update tuser set nickname=?,email=?,PSNSIGNATURE=? where id=?",
							new String[] { user.getNickname(), user.getEmail(),
									user.getPsnsignature(),
									StringUtil.toString(user.getId()) });

			// 保存头像
			fileUploadService.saveFile();

			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_OK,
					StringUtil.RESULT_SUCESS_UPDATE);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_FAIL,
					StringUtil.RESULT_EXCEPTION);
		}
	}

	@Override
	public String getFriends(String rqinfos) {
		List list = null;
		try {
			JSONObject jsonObject = JSONObject.fromObject(rqinfos);
			String id = jsonObject.getString("userid");
			// 获取好友SQL
			String sql = "select id,nickname,photo from tuser where id in "
					+ "(select user2 from friendship where  status=2 and user1=?)";
			list = SqlHelper.executeQuery(sql, new String[] { id }, null);

			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_OK, list);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_FAIL,
					StringUtil.RESULT_EXCEPTION);
		}
	}

	@Override
	public String findFriends(String rqinfos) {
		List list = null;
		try {
			JSONObject jsonObject = JSONObject.fromObject(rqinfos);
			String info = jsonObject.getString("phone");
			// 寻找好友SQL
			String sql = "select id,nickname,photo from tuser where bind_phone=? or nickname=?";
			list = SqlHelper.executeQuery(sql, new String[] { info, info },
					null);

			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_OK, list);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_FAIL,
					StringUtil.RESULT_EXCEPTION);
		}
	}

	@Override
	public String uploadContacts(String rqinfos) {
		try {
			JSONObject jsonObject = JSONObject.fromObject(rqinfos);
			String id = jsonObject.getString("userid");
			JSONArray jsonArray = jsonObject.getJSONArray("contacts");
			String[] sqls = new String[jsonArray.size()];
			String[][] params = new String[jsonArray.size()][3];
			for (int i = 0; i < jsonArray.size(); i++) {
				jsonObject = jsonArray.getJSONObject(i);
				sqls[i] = "insert into contacts values(?,?,?)";
				params[i] = new String[] { id, jsonObject.getString("name"),
						jsonObject.getString("phone") };
			}

			SqlHelper.executeUpdate(sqls, params);
			// 搜索通讯录好友
			searchFriends(id);

			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_OK, "上传成功");
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_FAIL,
					"上传失败，请稍候再试");
		}

	}

	@Override
	public String downloadContacts(String rqinfos) {
		List list = null;
		try {
			JSONObject jsonObject = JSONObject.fromObject(rqinfos);
			String id = jsonObject.getString("userid");
			list = SqlHelper.executeQuery(
					"select name,phone from contacts where id=?",
					new String[] { id }, null);
			if (list == null) {
				return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_FAIL,
						"你木有上传过通讯录");
			} else {
				return JsonUtil
						.createRtJsonStr(StringUtil.RESULT_CODE_OK, list);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_FAIL,
					"下载失败，请稍候再试");
		}
	}

	@Override
	public String sendMyRequest(String rqinfos) {
		try {
			JSONObject jsonObject = JSONObject.fromObject(rqinfos);
			String userid = jsonObject.getString("userid");
			String friend = jsonObject.getString("friend");
			String userName = jsonObject.getString("username");

			// 插入SQL语句
			String sql = "insert into friendship(id,user1,user2,status,req_time) values(?,?,?,1,sysdate)";
			SqlHelper
					.executeUpdate(
							sql,
							new String[] {
									StringUtil.toString(SqlHelper
											.getTableId("friendship")), friend,
									userid });

			// 插入推送表
			sql = "insert into message(id,type,fromid,toid,msg) values(?,3,?,?,?)";
			SqlHelper
					.executeUpdate(
							sql,
							new String[] {
									StringUtil.toString(SqlHelper
											.getTableId("message")), userid,
									friend, userName + "请求加你为好友" });

			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_OK, "发送成功");
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_FAIL,
					StringUtil.RESULT_EXCEPTION);
		}
	}

	@Override
	public String getMyReceives(String rqinfos) {
		try {
			JSONObject jsonObject = JSONObject.fromObject(rqinfos);
			String userid = jsonObject.getString("userid");

			// SQL语句
			String sql = "select a.id,b.nickname,b.photo,to_char(req_time,'yyyy-MM-dd hh24:mi') req_time from friendship a "
					+ "inner join tuser b on a.user2=b.id where status=1 and a.user1=?";
			List list = SqlHelper.executeQuery(sql, new String[] { userid },
					null);

			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_OK, list);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_FAIL,
					StringUtil.RESULT_EXCEPTION);
		}
	}

	@Override
	public String delMyReceives(String rqinfos) {
		try {
			JSONObject jsonObject = JSONObject.fromObject(rqinfos);
			String userid = jsonObject.getString("userid");
			String username = jsonObject.getString("username");
			String friend = jsonObject.getString("friend");
			String rqid = jsonObject.getString("rqid");
			String result = jsonObject.getString("result");

			if (result.equalsIgnoreCase("2")) {
				// 插入SQL语句
				String sql = "insert into friendship(id,user1,user2,status,req_time) values(?,?,?,2,sysdate)";
				SqlHelper.executeUpdate(
						sql,
						new String[] {
								StringUtil.toString(SqlHelper
										.getTableId("friendship")), userid,
								friend });
			}

			// 更新状态
			String sql = "update friendship set status=? where id=?";
			SqlHelper.executeUpdate(sql, new String[] { result, rqid });

			// 插入推送表
			String msg = null;
			if (result.equalsIgnoreCase("2")) {
				msg = username + "同意了您的好友请求";
			} else if (result.equalsIgnoreCase("3")) {
				msg = username + "拒绝了您的好友请求";
			}
			sql = "insert into message(id,type,fromid,toid,msg) values(?,3,?,?,?)";
			SqlHelper
					.executeUpdate(
							sql,
							new String[] {
									StringUtil.toString(SqlHelper
											.getTableId("message")), userid,
									friend, msg });

			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_OK, null);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.createRtJsonStr(StringUtil.RESULT_CODE_FAIL,
					StringUtil.RESULT_EXCEPTION);
		}
	}

	@Override
	public void searchFriends(String userId) {
		try {
			String sql = "select wm_concat(name) friends from contacts where phone in(select bind_phone from tuser) and id=?";
			List list = SqlHelper.executeQuery(sql, new String[] { userId },
					null);
			String msg = null;
			if (list.size() > 0 && !((Map) list.get(0)).isEmpty()) {
				msg = (String) ((Map) list.get(0)).get("friends");
			}

			if (!StringUtil.isNull(msg)) {
				sql = "insert into message(id,type,fromid,toid,msg) values(?,3,?,?,?)";
				SqlHelper.executeUpdate(
						sql,
						new String[] {
								StringUtil.toString(SqlHelper
										.getTableId("message")), userId,
								userId, msg });
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
